import { RetweetOutlined } from "@ant-design/icons"
import { Button, Flex } from "antd"
import { FC, useCallback, useEffect, useState } from "react"

import { queryMemberLoginLog } from "@/api/member"
import { IMemberList } from "@/api/member/types"
import { IMemberParams } from "@/api/risk/types"
import { DataList } from "@/components/common"
import { StyleTable } from "@/components/common/styled"
import { usePagination } from "@/hooks"
import { useLocale } from "@/locales"

import { columnsLoginInfomation } from "./TableInfo"
export const LoginInfo: FC<{ data: IMemberParams }> = ({ data }) => {
	const [dataLoginInfo, setDataLoginInfo] = useState({} as IMemberList)
	const { formatMessage } = useLocale()

	const { pagination, onPageChange } = usePagination(100)
	const handleGetMember = useCallback(
		async (isRefresh?: boolean) => {
			const body = {
				businessModel: data.businessModel,
				clubId: data.clubId,
				currency: data.currency,
				merchantId: data.merchantId,
				topProxyName: data.topProxyName,
				userId: data.userId,
				userName: data.username
			}

			const [err, MemberLoginLogRes] = await queryMemberLoginLog(
				!isRefresh ? { ...body, ...pagination } : { ...body, ...pagination, pageNum: 1 }
			)
			if (!err) setDataLoginInfo(MemberLoginLogRes)
		},
		[data, pagination]
	)
	useEffect(() => {
		// this will help to refresh pagination when upper actions are changed
		if (data.userId) handleGetMember(true)
	}, [data])
	useEffect(() => {
		handleGetMember()
	}, [pagination])

	return (
		<StyleTable>
			<Flex gap={10}>
				<Button className="title-login-info">{formatMessage({ id: "member.login_info" })}</Button>
				<Button icon={<RetweetOutlined />} onClick={() => handleGetMember(true)} type="primary">
					{formatMessage({ id: "member.refresh" })}
				</Button>
			</Flex>

			<p>
				<DataList
					data={dataLoginInfo.record}
					columns={columnsLoginInfomation(formatMessage)}
					defaultScrollY={300}
					bordered
					size="middle"
					pagination={{
						pageSize: dataLoginInfo.pageSize,
						current: dataLoginInfo.pageNum,
						total: dataLoginInfo.totalRecord,
						showSizeChanger: true
					}}
					onChange={onPageChange}
				/>
			</p>
		</StyleTable>
	)
}
